﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.ModelBinding;
using BrnMall.Business;
using BrnMall.Manager.Manager.AddressBook;
using BrnMall.Manager.Manager.Store;
using BrnMall.Manager.Manager.User;
using BrnMall.Manager.Manager.WeApp;
using BrnMall.Sdk.WeiXin.Tool;
using BrnMall.Services;
using BrnMall.Services.WJK;
using BrnMall.WeiXin.Sdk;
using BrnMall.WeiXin.Sdk.Domain;
using Newtonsoft.Json;
using WeiTap.Restful.Result;

namespace QIDong.WeApp.Controllers
{
    /// <summary>
    /// WebIMCallback
    /// </summary>
    public class WebIMCallbackController : ApiController
    {
        /// <summary>
        /// 消息回调
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string SendMsgCallback(string SdkAppid, string CallbackCommand, string ClientIP, string OptPlatform)
        {
            try
            {
                var result = JsonConvert.SerializeObject(new MsgCallbackRes { ActionStatus = "OK", ErrorCode = 0, ErrorInfo = "" });
                var httpContextWrapper = this.ControllerContext.Request.Properties["MS_HttpContext"] as HttpContextWrapper;
                if (httpContextWrapper == null) return result;
                httpContextWrapper.Request.InputStream.Position = 0;
                var bytes = httpContextWrapper.Request.BinaryRead(httpContextWrapper.Request.ContentLength);
                var stringBody = httpContextWrapper.Request.ContentEncoding.GetString(bytes);
                LogUtil.WriteLog(stringBody);
                var afterSendMsg = JsonConvert.DeserializeObject<CallbackAfterSendMsg>(stringBody);
                int touid = 0;
                int.TryParse(afterSendMsg.To_Account, out touid);
                int fromuid = 0;
                int.TryParse(afterSendMsg.From_Account, out fromuid);

                #region 下发单聊消息之后

                if (CallbackCommand.Equals("C2C.CallbackAfterSendMsg", StringComparison.InvariantCultureIgnoreCase))//单聊
                {

                    var fromPartUserInfo = Users.GetPartUserById(fromuid);
                    var toUidPartUserInfo = Users.GetPartUserById(touid);
                    var oauthInfo = OAuths.GetOAuthUserByUid(touid);
                    var staff = StaffManager.GetByUid(touid);
                    if (staff != null)//企业微信用户
                    {
                        //如果当前收到消息的企业账号登陆状态为离线，则发通知给他，走企业微信通道
                        //企业微信的授权企业
                        var perCode = WorkWeChats.GetAccessToken(toUidPartUserInfo.RegisterFromStoreId);
                        if (perCode == null)
                        {
                            LogUtil.WriteLog("获取perCode失败");
                            return result;
                        }
                        string msg = $"客户[{fromPartUserInfo.NickName}]给你发送了一条聊天消息";
                        //发送消息
                        var resultHtml=BrnMall.WeiXin.Sdk.Work.WorkWeiXinSDK.SendTextMessage(msg, staff.wxUserId, perCode.agentid, perCode.access_token);
                        LogUtil.WriteLog(resultHtml);

                    }
                    else if (oauthInfo.Server.Equals("weapp"))//小程序客户
                    {
                        if (UsersManager.CheckIMOnline(touid)) return result;
                        var storeWeApp = StoreApplicationManager.GetStoreApplication(toUidPartUserInfo.StoreAppId);
                        if (storeWeApp == null) return result;
                        StoreAppReleaseManager.RefreshAuthorizerToken(storeWeApp.StoreAppId);
                        var authInfo = AppAuthorizationManager.GetAppAuthorization(storeWeApp.AuthorizationId);
                        if (authInfo == null) return result;
                        var storewxapp = StoreWxAppManager.GetStoreWxAppByAppId(authInfo.Authorizer_Appid);
                        if (storewxapp == null) return result;
                        //如果当前收到消息的小程序账号登陆状态为离线，则发通知给他,走小程序通过
                        var formId = WeAppFormIDManager.GetFormIdByUid(touid);
                        if (formId == null) { return result; }
                        var data = new TemplateData
                        {
                            keyword1 = new TemplateKeyWord { value = fromPartUserInfo.NickName },
                            keyword2 = new TemplateKeyWord { value = DateTime.Now.ToString("yyyy-MM-dd hh:mm") },
                            keyword3 = new TemplateKeyWord { value = "您有未读消息" }
                        };
                        SendTemplateMessage.PostSendMsgSuccess(authInfo.Authorizer_Access_Token, formId.OpenId, storewxapp.SendMsgCallbackTid, formId.FormId, data);
                        WeAppFormIDManager.Delete(formId.Id);
                        LogUtil.WriteLog("发通知给小程序用户");
                    }
                }

                #endregion

                #region 用户状态变更，上线，下线

                if (CallbackCommand.Equals("State.StateChange", StringComparison.InvariantCultureIgnoreCase)) //用户状态变更
                {
                    if (afterSendMsg.Action.Equals("Login", StringComparison.InvariantCultureIgnoreCase)) //上线
                    {
                        UsersManager.UpdateUserIMState(touid, true);
                    }
                    else //下线
                    {
                        UsersManager.UpdateUserIMState(touid, false);
                    }
                }


                #endregion


                return result;
            }
            catch (Exception e)
            {
                
                LogUtil.WriteLog(e.Message);
                LogUtil.WriteLog(e.StackTrace);
                LogUtil.WriteLog(e.Source);
                LogUtil.WriteLog(e.InnerException?.Message??"");
                throw;
            }
            

        }
    }

    public class CallbackAfterSendMsg
    {
        public string CallbackCommand { get; set; }
        public string From_Account { get; set; }
        public string To_Account { get; set; }
        public string Action { get; set; }
    }

    public class MsgCallbackRes
    {
        public string ActionStatus { get; set; }
        public string ErrorInfo { get; set; }
        public int ErrorCode { get; set; }
    }
}
